// 安全拦截器
const jwt = require("jsonwebtoken");
/**
 * 验证权限，异步
 * @param token
 * @param secretkey 秘钥
 * @param success
 * @param error
 */
function verify (token,secretkey,success,error){
    jwt.verify(token,secretkey,function(err,decode){//回调
        if(err){
            if (error) {
                error(err);
            }
        }else{
            if (success) {
                success(decode);
            }
        }
    })
}
/**
 * 签名
 * @param load 载荷 json对象 存储存在
 * @param secretkey 秘钥
 * @param expiresIn 过期时间 秒
 * @returns {number | PromiseLike<ArrayBuffer>}
 */
function sign (load,secretkey,expiresIn) {
    var token = jwt.sign(load,secretkey,{expiresIn: expiresIn});
    return token;
}

/**
 * 同步
 * @param token
 * @param secretkey
 * @returns {Promise<any>}
 */
function verifysync (token,secretkey){
    return new Promise((resolve, reject) => {
        jwt.verify(token,secretkey,function(err,decode){
            if(err){
                console.log(err.message)
                resolve({err:'error',msg:'会话已过期，请重新登录'})
            }else{
                resolve(decode)
            }
        })
    })
}
module.exports = {verify,sign,verifysync};

// 实际应用
let user = {id:111,name:'user',password:123456};
delete user.password;
let token = sign(user, '123456', 10);
// let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTExLCJuYW1lIjoidXNlciIsImlhdCI6MTU5NjE3OTkwNSwiZXhwIjoxNTk2MTc5OTE1fQ.dfoZXJ6_38o2MrkHLpgiCzQVZG8QnLY5TUAZaofNZx8'
verify(token,'123456',function (user) {
    console.log(user)
},function (err) {
    console.error(err)
})